package io.renren.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.renren.dao.InterviewDao;
import io.renren.entity.CustomSettlementEntity;
import io.renren.entity.InterviewEntity;
import io.renren.utils.Global;
import io.renren.utils.HttpClientUtils;
import io.renren.utils.Sha1Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.renren.dao.RecruitdamandDao;
import io.renren.entity.RecruitdamandEntity;
import io.renren.service.RecruitdamandService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional(propagation= Propagation.REQUIRED)
@Service("recruitdamandService")
public class RecruitdamandServiceImpl implements RecruitdamandService {
    /**
     * 日志对象
     */
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RecruitdamandDao recruitdamandDao;

    @Autowired
    private InterviewDao interviewDao;

    @Override
    public RecruitdamandEntity queryObject(Integer id) {
        return recruitdamandDao.queryObject(id);
    }

    @Override
    public List<RecruitdamandEntity> queryList(Map<String, Object> map) {
        return recruitdamandDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return recruitdamandDao.queryTotal(map);
    }

    @Override
    public void save(RecruitdamandEntity recruitdamand) {
        recruitdamandDao.save(recruitdamand);
    }

    @Override
    public void update(RecruitdamandEntity recruitdamand) {
        recruitdamandDao.update(recruitdamand);
    }

    @Override
    public void delete(Integer id) {
        recruitdamandDao.delete(id);
    }

    @Override
    public void deleteBatch(Integer[] ids) {
        recruitdamandDao.deleteBatch(ids);
    }

    @Override
    @Transactional
    public void syncRecruitDamandFormB1(Map<String, Object> map) {
        List<RecruitdamandEntity> info = new ArrayList<>();

        logger.info("与b1进行数据同步开始");
        Map<String, Object> params = new HashMap<String, Object>();
        String key = Global.getConfig("b1key");// 获取key
        String url = Global.getConfig("b1url8");// 获取url
        logger.info("key:" + key);
        logger.info("url:" + url);

        String sign = Sha1Util.SHA1(params, key);// 计算签名
        logger.info("sign:" + sign);
        params.put("sign", sign);

        String result = null;

        try {
            result = HttpClientUtils.doPost(url, params);// 发送请求
            JSONObject json = JSONObject.parseObject(result);
            JSONArray jarray = json.getJSONArray("data");
            for (Object o : jarray) {
                JSONObject j = JSONObject.parseObject(o.toString());
                //if(j.getString("u_type").equals("0")){
                    JSONArray ja = j.getJSONArray("item");
                    for (Object obj : ja) {
                        JSONObject jobj = JSONObject.parseObject(obj.toString());
                        RecruitdamandEntity recruit = new RecruitdamandEntity();
                        CustomSettlementEntity sett = recruitdamandDao.selectSettlementByNO(j.getString("cardCode"));
                        if(sett==null){
                            logger.info("info",j.getString("cardCode")+"结算点的求职需求无法匹配结算点！");
                            return ;
                        }
                        recruit.setSettlementid(sett.getId());
                        recruit.setSettlementno(j.getString("cardCode"));
                        recruit.setSettlementname(j.getString("cardName"));
                        recruit.setDamandid(j.getString("docEntry"));
                        recruit.setJobid(jobj.getString("itemCode"));
                        recruit.setJobname(jobj.getString("dscription"));
                        recruit.setEmpnum(jobj.getInteger("quantity"));
                        recruit.setFinishdate(j.getDate("docDueDate"));
                        recruit.setSex(jobj.getString("u_xb"));
                        recruit.setLowage(jobj.getInteger("u_nlq"));
                        recruit.setTopage(jobj.getInteger("u_nlz"));
                        recruit.setEducation(jobj.getString("u_xl"));
                        recruit.setMarried(jobj.getString("u_hf"));
                        recruit.setCertificatename(jobj.getString("u_gzzj"));
                        info.add(recruit);

                        //返回数据执行状态给B1
                        JSONObject data = new JSONObject();
                        data.put("docEntry",j.getString("docEntry"));
                        JSONObject j1 = new JSONObject();
                        j1.put("itemCode",jobj.getString("itemCode"));
                        j1.put("quantity",jobj.getInteger("quantity"));
                        JSONArray ar = new JSONArray();
                        ar.add(j1);
                        data.put("item",ar);
                        Map<String, Object> ret = new HashMap<>();
                        ret.put("data",data.toJSONString());
                        String retsign = Sha1Util.SHA1(ret, "huashun");// 计算签名
                        System.out.println("data:"+data.toJSONString()+";sign:"+retsign);
                        JSONObject doc = new JSONObject();
                        doc.put("data",data.toJSONString());
                        doc.put("sign",retsign);
                        String url1 = Global.getConfig("b1url20");// 获取url
                        /*URL uploadServlet = new URL(url1);
                        HttpURLConnection servletConnection = (HttpURLConnection) uploadServlet.openConnection();
                        // 设置连接参数
                        servletConnection.setRequestMethod("POST");
                        servletConnection.setDoOutput(true);
                        servletConnection.setDoInput(true);
                        servletConnection.setAllowUserInteraction(true);

                        // 开启流，写入XML数据
                        OutputStream output = servletConnection.getOutputStream();
                        output.write(doc.toString().getBytes());
                        output.flush();
                        output.close();*/
                        String retresult = HttpClientUtils.doPost(url1, doc);
                        logger.info("info",retresult);

                    }
                //}
            }

            if(info!=null&&info.size()>0){
                recruitdamandDao.syncRecruitDamandFormB1(info);
                logger.info("info", "同步数据成功!");
            }else{
                logger.info("info","没有需要同步的数据!");
            }

        } catch (Exception ex) {
            logger.info("error", "同步数据失败!");
            ex.printStackTrace();
        }

    }

    @Override
    public List<Map<String, Object>> choosePerson(JSONArray ids) {
        List<Map<String, Object>> res = new ArrayList<>();
        for (Object id : ids) {
            Map<String, Object>  map = new HashMap<String, Object>();
            RecruitdamandEntity recruitdamand = queryObject(Integer.valueOf(id.toString()));
            int personnum = recruitdamand.getEmpnum();
            map.put("company",recruitdamand.getSettlementid());
            map.put("job",recruitdamand.getJobid());//岗位为字典后jobid没有意义
            map.put("job",recruitdamand.getJobname());

            map.put("sex",recruitdamand.getSex());
            map.put("topage",recruitdamand.getTopage());
            map.put("lowage",recruitdamand.getLowage());
            map.put("papername",recruitdamand.getCertificatename());
            List<Map<String, Object>> result = recruitdamandDao.choosePerson(map);
            if(result.size()<personnum*2){
                map.remove("papername");
                result = recruitdamandDao.choosePerson(map);
                if(result.size()<personnum*2){
                    map.remove("lowage");
                    result = recruitdamandDao.choosePerson(map);
                    if(result.size()<personnum*2){
                        map.remove("sex");
                        result = recruitdamandDao.choosePerson(map);
                    }
                }
            }
            res.addAll(result);
            for (Map<String, Object> re : res) {
                re.put("damandid",recruitdamand.getDamandid());
                re.put("settlementid",recruitdamand.getSettlementid());
                re.put("settlementno",recruitdamand.getSettlementid());

                re.put("settlementname",recruitdamand.getSettlementname());
                re.put("jobid",recruitdamand.getJobid());
                re.put("jobname",recruitdamand.getJobname());
            }
        }
        return res;
    }

    @Override
    @Transactional
    public int selectedEmp(JSONArray jsonArray,String id ) {

        int res = 0;
        try{
            RecruitdamandEntity recruitdamandEntity = new RecruitdamandEntity();
            recruitdamandEntity.setId(Integer.valueOf(id));
            recruitdamandEntity.setJoinfircount(jsonArray.size());
            recruitdamandDao.updatePeople(recruitdamandEntity);
            for(int i = 0; i<jsonArray.size(); i++){
                JSONObject json = jsonArray.getJSONObject(i);
                InterviewEntity inter = new InterviewEntity();
                inter.setRecruitdamandid(id);
                inter.setDamandid(json.getString("damandid"));
                inter.setAge(json.getInteger("age"));
                inter.setEducation(json.getString("education"));
                inter.setJobid(json.getString("jobid"));
                inter.setJobname(json.getString("jobname"));
                inter.setMarried(json.getString("married"));
                inter.setEmpname(json.getString("name"));
                inter.setEmpid(json.getInteger("id"));
                inter.setCertificate(json.getString("certificate"));
                inter.setSex(json.getString("sex"));
                inter.setCompany(json.getString("settlementname"));
                inter.setCompanyid(json.getString("settlementid"));
                inter.setCompanyid(json.getString("settlementno"));

                inter.setFirInterviewStatus("0");

                interviewDao.save(inter);
                recruitdamandDao.changeFreeFlag(json.getInteger("id"));
                res = 1;
            }
        }catch (Exception e){
            res = 0;
            e.printStackTrace();
        }
        return res;
    }

}
